#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{

    ui->setupUi(this);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(flushTime()));
}

Widget::~Widget()
{
    delete ui;
}

QString Widget::formatTime(int ms) const
{
    int ss = 1000;
    int mi = ss * 60;
    int hh = mi * 60;
    int dd = hh * 24;

    long day = ms / dd;
    long hour = (ms - day * dd) / hh;
    long minute = (ms - day * dd - hour * hh) / mi;
    long second = (ms - day * dd - hour * hh - minute * mi) / ss;
    long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

    QString hou = QString::number(hour,10);
    QString min = QString::number(minute,10);
    QString sec = QString::number(second,10);
    QString msec = QString::number(milliSecond,10);

    //qDebug() << "minute:" << min << "second" << sec << "ms" << msec <<endl;

    return hou + ":" + min + ":" + sec;
}

void Widget::on_pushButton_clicked()
{
    QString text = ui->pushButton->text();
    if (text == "start")
    {
        ui->pushButton->setText("stop");
        startTime = QTime::currentTime();
        startTime.start();
        timer->start(200);
    }
    else
    {
        timer->stop();
        ui->lcdNumber->display(0);
        ui->pushButton->setText("start");
    }
}

void Widget::flushTime()
{
    auto durtion = startTime.elapsed();
    QString text = formatTime(durtion);
    ui->lcdNumber->display(text);
}
